package org.chen.service.impl;

import com.alibaba.nacos.common.utils.StringUtils;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.chen.domain.dto.UpdatePasswordDTO;
import org.chen.domain.dto.UserQueryDTO;
import org.chen.domain.entity.Role;
import org.chen.domain.entity.User;
import org.chen.domain.response.PageResult;
import org.chen.domain.vo.UserVO;
import org.chen.mapper.UserMapper;
import org.chen.security.SecurityUtils;
import org.chen.service.UserService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.stream.Collectors;

@Service
@Transactional
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService {
    @Autowired
    private UserMapper userMapper;
    
    @Autowired
    private PasswordEncoder passwordEncoder;
    
    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        User user = userMapper.selectOne(
            new LambdaQueryWrapper<User>()
                .eq(User::getUsername, username)
        );
        
        if (user == null) {
            throw new UsernameNotFoundException("用户不存在");
        }
        
        List<Role> roles = userMapper.selectUserRoles(user.getId());
        List<GrantedAuthority> authorities = roles.stream()
            .map(role -> new SimpleGrantedAuthority("ROLE_" + role.getRoleKey()))
            .collect(Collectors.toList());
            
        return new org.springframework.security.core.userdetails.User(
            user.getUsername(),
            user.getPassword(),
            authorities
        );
    }
    
    @Override
    public UserVO getCurrentUserInfo() {
        String username = SecurityUtils.getCurrentUsername();
        User user = userMapper.selectOne(
            new LambdaQueryWrapper<User>()
                .eq(User::getUsername, username)
        );
        
        UserVO userVO = new UserVO();
        BeanUtils.copyProperties(user, userVO);
        
        List<Role> roles = userMapper.selectUserRoles(user.getId());
        userVO.setRoles(roles.stream()
            .map(Role::getRoleKey)
            .collect(Collectors.toList()));

        return userVO;
    }
    
    @Override
    public void updatePassword(UpdatePasswordDTO dto) {
        String username = SecurityUtils.getCurrentUsername();
        User user = userMapper.selectOne(
            new LambdaQueryWrapper<User>()
                .eq(User::getUsername, username)
        );
        
        if (!passwordEncoder.matches(dto.getOldPassword(), user.getPassword())) {
            throw new BadCredentialsException("原密码不正确");
        }
        
        user.setPassword(passwordEncoder.encode(dto.getNewPassword()));
        userMapper.updateById(user);
    }
    
    @Override
    public PageResult<UserVO> getUserList(UserQueryDTO query) {
        Page<User> page = new Page<>(query.getPageNum(), query.getPageSize());
        
        LambdaQueryWrapper<User> wrapper = new LambdaQueryWrapper<User>()
            .like(StringUtils.hasText(query.getUsername()), User::getUsername, query.getUsername())
            .like(StringUtils.hasText(query.getEmail()), User::getEmail, query.getEmail())
            .eq(query.getStatus() != null, User::getStatus, query.getStatus());
            
        Page<User> userPage = userMapper.selectPage(page, wrapper);
        
        List<UserVO> userVOs = userPage.getRecords().stream()
            .map(user -> {
                UserVO vo = new UserVO();
                BeanUtils.copyProperties(user, vo);
                List<Role> roles = userMapper.selectUserRoles(user.getId());
                vo.setRoles(roles.stream()
                    .map(Role::getRoleKey)
                    .collect(Collectors.toList()));
                return vo;
            })
            .collect(Collectors.toList());
            
        return new PageResult<>(userVOs, userPage.getTotal());
    }

    /**
     * 检查用户是否有指定权限
     */
    public boolean hasPermission(String permission) {
        try {
            UserVO currentUser = getCurrentUserInfo();
            // 这里可以根据实际需求实现更复杂的权限判断逻辑
            // 比如查询用户角色、角色权限等
            return currentUser != null && currentUser.getStatus() == 1;
        } catch (Exception e) {
            return false;
        }
    }
}